package com.sphsine.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.SsoJsonResult;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.entity.User;
import com.javaweb.system.entity.UserOrg;
import com.javaweb.system.mapper.UserOrgMapper;
import com.javaweb.system.service.IUserRoleService;
import com.javaweb.system.service.IUserService;
import com.javaweb.system.utils.RandomPassword;
import com.javaweb.system.utils.ShiroUtils;
import com.sphsine.sso.entity.AccountBody;
import com.sphsine.sso.entity.AccountMsgData;
import com.sphsine.sso.entity.MsgBody;
import com.sphsine.sso.entity.SsoOrg;
import com.sphsine.sso.enums.OperType;
import com.sphsine.sso.mapper.SsoOrgMapper;
import com.sphsine.sso.service.AccountService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    IUserService userService;
    @Autowired
    UserOrgMapper userOrgMapper;

    @Autowired
    SsoOrgMapper ssoOrgMapper;

    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public SsoJsonResult syncaccount(AccountMsgData data) {
        String operType = "";
        AccountBody body = null;
        try {
            if(StringUtils.isNull(data) || StringUtils.isNull(data.getMsgBody())){
                return SsoJsonResult.error(1,"msgBody不能为空");
            }
            body= data.getMsgBody();
            operType = OperType.valueOf("UPDATED").name().toUpperCase();
            //检验opertype
            Map<String, Boolean> enumMap = new HashMap<>();
            enumMap.put(OperType.CREATED.name(), true);
            enumMap.put(OperType.UPDATE.name(), true);
            enumMap.put(OperType.UPDATED.name(), true);
            if (!enumMap.containsKey(body.getOpertype())) {
                return SsoJsonResult.error("操作类型:"+body.getOpertype()+"无效,必须是CREATED或UPDATED");
            }
            if(StringUtils.isEmpty(body.getUsername())){
                return SsoJsonResult.error("用户账号不能为空");
            }
            if(StringUtils.isEmpty(body.getFullname())){
                return SsoJsonResult.error("用户姓名不能为空");
            }
            if(StringUtils.isNull(body.getOrgid())){
                return SsoJsonResult.error("用户所属组织主键不能为空");
            }
            //若是修改，uguid必须输入
            if(body.getOpertype().toUpperCase().equals(operType)) {
                if(StringUtils.isEmpty(body.getUguid())){
                    return SsoJsonResult.error("更新账号，uguid必须输入");
                }
            }

            Map<String,Object> param = new HashMap<>();
            param.clear();
            param.put("username",body.getUsername());
            User localUser = null;
            if(!StringUtils.isNull(body.getUguid())) {
                localUser = userService.getUser(Integer.parseInt(body.getUguid()));
            }
            //数据更新，判断id是否存在
            if(body.getOpertype().toUpperCase().equals(operType)) {
                if (localUser==null){
                    return SsoJsonResult.error(body.getUsername()+"不存在，更新用户账号失败");
                }
            }else{
                param.clear();
                param.put("username",body.getUsername());
                List<User> userList = userService.list(new QueryWrapper<User>().eq("username",body.getUsername()));
                if (userList.size() > 0){
                    return SsoJsonResult.success("",userList.get(0).getId().toString());
                }
            }
            User entity = new User();
            UserOrg userOrg = new UserOrg();
            entity.setUsername(body.getUsername());
            entity.setRealname(body.getFullname());
            entity.setMobile(body.getMobile());
            entity.setEmail(body.getEmail());
            entity.setDeptId(body.getOrgid());
            if(!body.getOpertype().toUpperCase().equals(operType)) {
                String defPassword = RandomPassword.getDefaultRandomPassword();
                entity.setPassword(CommonUtils.password(defPassword));
                entity.setSalt(defPassword);
            }
            String[] orgCode = new String[1];
            SsoOrg ssoOrg = ssoOrgMapper.selectById(body.getOrgid());
            if(!StringUtils.isNull(ssoOrg)){
                orgCode[0] =ssoOrg.getOrgcode();
            }
            if(body.getOpertype().equals(operType)) {
                entity.setId(Integer.parseInt(body.getUguid()));
                entity.setUpdateTime(DateUtils.now());
                entity.setUpdateUser(Integer.parseInt(body.getUguid()));
                //用户禁用，设置status=2
                if(body.getIsdisabled()){
                    entity.setStatus(2);
                }else{
                    entity.setStatus(1);
                }
                userService.edit(entity);
                //ssoOrgMapper.updateById(entity);
            }else{
                entity.setCreateUser(0);
                entity.setCreateTime(DateUtils.now());
                //ssoOrgMapper.insert(entity);
                userService.edit(entity);
                //根据组织主键获取组织代码

            }
            // 删除已存在的用户角色关系数据
            if(!StringUtils.isEmpty(orgCode[0])) {
                //userRoleService.deleteUserOrg(entity.getId());
                // 插入用户角色关系数据
                //userRoleService.insertUserOrg(entity.getId(), orgCode);
            }

            return SsoJsonResult.success("",entity.getId().toString());
        }
        catch(Exception ex) {
            if(body.getOpertype().toUpperCase().equals(operType)){
                if(ex.getMessage().toLowerCase().contains("duplicate")){
                    return SsoJsonResult.error(1, "用户账号更新失败:" + data.getMsgBody().getUsername()+"已存在");
                }else {
                    return SsoJsonResult.error(1, "用户账号更新失败。" + ex.getMessage());
                }
            }else{
                return SsoJsonResult.error(1,"用户账号创建失败。"+ex.getMessage());
            }
        }
    }
}
